package com.example.demo.time;

import com.example.demo.entity.Notice;
import com.example.demo.entity.Sch_remind;
import com.example.demo.entity.User;
import com.example.demo.utils.HttpUtils;
import jakarta.annotation.Resource;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.net.http.HttpResponse;

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.*;

//这是调来发送日程提醒和通知的?要群发吗，难搞
@Component
public class Executetime {

    private static final Logger log = LoggerFactory.getLogger(Executetime.class);

    @Resource
    JavaMailSender javaMailSender;

    /*
     * 指定时间执行一次定时任务
     *
     * @param localDateTime 触发时机
     * @param timing        参数信息
     */
    public void timing_sch(LocalDateTime localDateTime, Sch_remind sch_remind, User user) {
        Calendar calendar = Calendar.getInstance();
        // 年份
        calendar.set(Calendar.YEAR, localDateTime.get(ChronoField.YEAR));
        // 月份 传入日期需要-1
        calendar.set(Calendar.MONTH, localDateTime.get(ChronoField.MONTH_OF_YEAR)-1);
        // 天数
        calendar.set(Calendar.DAY_OF_MONTH, localDateTime.get(ChronoField.DAY_OF_MONTH));
        // 小时
        calendar.set(Calendar.HOUR_OF_DAY, localDateTime.get(ChronoField.HOUR_OF_DAY));
        // 分钟
        calendar.set(Calendar.MINUTE, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
        // 秒
        calendar.set(Calendar.SECOND, localDateTime.get(ChronoField.SECOND_OF_MINUTE));
        Date time = calendar.getTime();
//        Date time = new Date();
        Timer timer = new Timer();
        // 执行
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                if(sch_remind.getMethod().equals("邮箱"))
                {
                    if(user.getEmail()==null){
                        return;
                    }
                    SimpleMailMessage message = new SimpleMailMessage();
                    try {
                        message.setFrom(new InternetAddress(MimeUtility.encodeText("活动管理系统官方: ")+"<1973834626@qq.com>").toString());
                        message.setTo(user.getEmail());
                        message.setSubject("日程提醒");
                        message.setText("您参与的活动开始了新日程");
                        javaMailSender.send(message);
                        //return PlannerResult.success("日程提醒已发送");
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        //return PlannerResult.error("邮件发送失败");
                    }


                }
                else {

                    //短信api调用地址
                    String host = "https://dfsns.market.alicloudapi.com";
                    //请求路径
                    String path = "/data/send_sms";
                    //请求方式
                    String method = "POST";
                    //appcode：自己的AppCode，可以在自己的控制台找到，是一串32位的字符串
                    String appcode = " ";
                    Map<String, String> headers = new HashMap<String, String>();
                    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
                    headers.put("Authorization", "APPCODE " + appcode);
                    //根据API的要求，定义相对应的Content-Type
                    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    Map<String, String> querys = new HashMap<String, String>();
                    Map<String, String> bodys = new HashMap<String, String>();

                    //使用随机数生成4位验证码
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("您参与的活动开始了新日程");

                    String code = stringBuilder.toString();
                    //这里是要发送给用户的验证码，我们使用了随机数进行生成
                    bodys.put("content", "code:"+code);
                    //这里是接受短信的手机号码，我们在实际开发时这里就不能写死了
                    bodys.put("phone_number", "176****5321");
                    //这里是发送短信的模板ID：代表整体短信文案模板
                    bodys.put("template_id", "TPL_0000");
                    try {
                        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                        System.out.println(response.toString());
                        //获取response的body
                        //System.out.println(EntityUtils.toString(response.getEntity()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

            }
        }, time);

    }



    public void timing_notice(LocalDateTime localDateTime, Notice notice, User user) {
        Calendar calendar = Calendar.getInstance();
        // 年份
        calendar.set(Calendar.YEAR, localDateTime.get(ChronoField.YEAR));
        // 月份 传入日期需要-1
        calendar.set(Calendar.MONTH, localDateTime.get(ChronoField.MONTH_OF_YEAR)-1);
        // 天数
        calendar.set(Calendar.DAY_OF_MONTH, localDateTime.get(ChronoField.DAY_OF_MONTH));
        // 小时
        calendar.set(Calendar.HOUR_OF_DAY, localDateTime.get(ChronoField.HOUR_OF_DAY));
        // 分钟
        calendar.set(Calendar.MINUTE, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
        // 秒
        calendar.set(Calendar.SECOND, localDateTime.get(ChronoField.SECOND_OF_MINUTE));
        Date time = new Date();
        Timer timer = new Timer();
        // 执行
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                SimpleMailMessage message = new SimpleMailMessage();
                try {
                    message.setFrom(new InternetAddress(MimeUtility.encodeText("活动管理系统官方: ")+"<1973834626@qq.com>").toString());
                    message.setTo(user.getEmail());

                    message.setSubject(notice.getNotice_type_id().toString());
                    message.setText(notice.getContext());

                    //测试用
//                    System.out.println(message);
                    javaMailSender.send(message);
                    //return PlannerResult.success("日程提醒已发送");
                } catch (Exception e) {
                    //return PlannerResult.error("邮件发送失败");
                }
            }
        }, time);
    }
}
